<?php
class CCreateUser
{
    // Array of columns
    private $column = array(
        "benutzername" => null,
        "vorname" => null,
        "name" => null,
        "e-mail" => null,
        "gstelleId" => null,
        "filialeId" => null,
        "bezirkId" => null,
        "zentraleId" => null,
        "passwd" => null,
        "passwd_datum" => null,
        "status" => null,
        "rechte" => null,
        "inBearbeitung" => 0,
        "bearbeiterId" => null
    );
   
    private $userId = null;
    private $origPassword = null;
    
    // Sets mandatory fields
    public function setUsername($value) { $this->column['benutzername'] = $value; }
    public function setPasswd($value) { $this->column['passwd'] = $value; }
    public function setPasswdDatum($value) { $this->column['passwd_datum'] = $value; }
    // --
    public function setVorname($value) { $this->column['vorname'] = $value; }
    public function setName($value) { $this->column['name'] = $value; }
    public function setEmail($value) { $this->column['e-mail'] = $value; }
    public function setGstelleID($value) { $this->column['gstelleId'] = $value; }
    public function setFilialeID($value) { $this->column['filialeId'] = $value; }
    public function setBezirkID($value) { $this->column['bezirkId'] = $value; }
    public function setZentraleID($value) { $this->column['zentraleId'] = $value; }
    public function setStatus($value) { $this->column['status'] = $value; }
    public function setRechte($value) { $this->column['rechte'] = $value; }
    public function setInBearbeitung($value) { $this->column['inBearbeitung'] = $value; }
    public function setBearbeiterId($value) { $this->column['bearbeiterId'] = $value; }
    
    public function getUsername() { return $this->column['benutzername']; }


    
    // Generates an username
    /**
     * @todo Umwandlung der ToDo's
     * Enter description here ...
     */
    private function genUsername() 
    {       
        // Username
        $username;
        $vorname = $this->column['vorname'];
        $name = $this->column['name'];
        
        // if vorname or name empty or null, abort.
        if($vorname == null || $vorname == "" || $name == null || $name == "")
        {
            $username = null;
            return;
        }

        // Set the prename-character to lower 
        $username = strtolower($vorname[0]);
        
        // -- 
        $name = strtolower($name);
        

        
        
        
        // Concat $name to $username
        $username.= $name;
        
        $tempUsername = $username;
        
        // Check if username already exists
        $i=0;
        while($this->exists($tempUsername)) {
            $i++;
            $tempUsername = $username . $i;            
        }
        $username = $tempUsername;
        
        // Convert 'ae', 'oe', 'ue'
        $username = str_replace("ä", "ae", $username);
        $username = str_replace("ö", "oe", $username);
        $username = str_replace("ü", "ue", $username);

        // Return the username
        return $username;
    }
    
    
    public function setPasswordExt($pw) 
    {
        $this->origPassword = $pw;
    }
    
    /**
	 * Das Passwort darf mit dem zuletzt benutzten Passwort nicht identisch sein. 
	 * Zudem muss es achtstellig sein und mindestens ein Sonderzeichen und 
	 * einen Gro�buchstaben aufweisen.
     */
    public function genPassword()
    {
        // Zeichenlaenge
        $pw_laenge = 8;
        $password = array();
        $upper_letters = range('A','Z');
        $lower_letters = range('a','z');
        $special_chars = array('#','&','@','$','_','%','?','+', '!', '§', '/', '(', ')', '=');
        
        // merge arrays
        $merged_array = array_merge($upper_letters, $lower_letters, $special_chars);
        
        // Create password
        for($i=0; $i<$pw_laenge; $i++)
        {
            // Get Index
            do {
                $index = rand(0, $pw_laenge-1);
            } while($password[$index] != null);
            
            // Get random character
            shuffle($merged_array);
            $rand_char = $merged_array[rand(0, count($merged_array)-1)];
            
            // Put char on $password[$index]
            $password[$index] = $rand_char;
        }
        
        $index = rand(0, $pw_laenge-1);
        $password[$index] = $upper_letters[ rand(0, count( $upper_letters)-1 ) ];
        $index = rand(0, $pw_laenge-1);
        $password[$index] = $special_chars[ rand(0, count( $special_chars)-1 ) ];
        
        // array to string
        $password = implode('', $password);
        
        return $password;
    }
    

    
    /**
     * 
     * Checks if username already exists
     * @param $value
     */
    private function exists($value)
    {
        // Fetching the user record
	    $sql = CSingleton::get("sql::sql");
	    $qry = $sql->prepare("SELECT 1 FROM Mitarbeiter WHERE benutzername = ?");
	    $qry->execute(array($value));
	    
	    // if username exists
	    if($qry->rowCount() == 0)
            return false;
        else
            return true;
    }
    
    private function createStmt()
    {
        $stmt = "INSERT INTO Mitarbeiter SET ";
        $values = array();
        foreach($this->column as $key => $value)
        {
            $stmt.= "`" . $key . "`" . " = ?,";
            $values[] = $value;
        }
        // cut off last ","
        $stmt = substr($stmt, 0, -1);
        
        // Datapackage
        $data[0] = $stmt;
        $data[1] = $values;
        
        return $data;
    }
    
    private function editStmt()
    {
        $stmt = "UPDATE Mitarbeiter SET ";
        $values = array();
        foreach($this->column as $key => $value)
        {
            $stmt.= "`" . $key . "`" . " = ?,";
            $values[] = $value;
        }
        // cut off last ","
        $stmt = substr($stmt, 0, -1);
        $stmt.= " WHERE idMitarbeiter = ?";
        
        // Datapackage
        $data[0] = $stmt;
        $data[1] = $values;
        
        return $data;
    }
    
    private function finalizeCopy()
    {
        $sql = CSingleton::get("sql::sql");
        $qry_get = $sql->prepare("SELECT passwd, passwd_datum FROM Mitarbeiter WHERE benutzername = ? AND inBearbeitung = 0");
        $qry_get->execute(array($this->column['benutzername']));
        $m = $qry_get->fetch(PDO::FETCH_ASSOC);
        $qry = $sql->prepare("UPDATE Mitarbeiter SET passwd = ?, passwd_datum = ? WHERE benutzername = ? AND inBearbeitung = 1");
        $qry->execute(array($m['passwd'], $m['passwd_datum'], $this->column['benutzername']));
    }
    
    // get generated password
    public function getGeneratedPassword()
    {
        return $this->origPassword;
    }
    
    // Creates an user
    public function create()
    {        
        // Generate username and password

        
        // Verify inputs stored in column[]
        if($this->verify())
        {
            $sql = CSingleton::get("sql::sql");
            
            // Neuer Datensatz
            if($this->column['inBearbeitung'] == 0)
            {
                $this->column['benutzername'] = $this->genUsername();
                $this->origPassword = $this->genPassword();
                $this->column['passwd'] = md5($this->origPassword);
                
                $this->column['passwd_datum'] = CUserAuth::genPasswordExpireDate();
                
                // SQL-Data
                $stmt = $this->createStmt();
                // Fetching user record
               
                $qry = $sql->prepare($stmt[0]);
                $qry->execute($stmt[1]);
                
            }
            // Datensatz editieren
            else if($this->column['inBearbeitung'] == 1)
            {
                // Falls noch kein doppelter datensatz existiert...
                if(($idDubRow = $this->getDublicatedRow()) == -1)
                {
                    $stmt = $this->createStmt();
                    $qry = $sql->prepare($stmt[0]);
                    $qry->execute($stmt[1]);
                    
                    // Letzten fehlenden Cells kopieren
                    $this->finalizeCopy();
                }
                // Falls doppelter Datensatz existiert...
                else
                {
                    $qry = $sql->prepare("UPDATE mitarbeiter SET vorname = ?, name = ?, `e-mail` = ?
                                         WHERE benutzername = ? AND inBearbeitung = 1");
                    $qry->execute(array($this->column['vorname'], $this->column['name'], $this->column['e-mail'], $this->column['benutzername']));
                    
                }
            }

        }
    }
    
    /**
     * Returns either the ID of a duplicated user row or -1,
     * if there's no second row 
     */
    private function getDublicatedRow()
    {
        $sql = CSingleton::get("sql::sql");
        $qry = $sql->prepare("SELECT 
                                  idMitarbeiter,
                                  inBearbeitung
                              FROM Mitarbeiter 
                              WHERE benutzername = ?
                              ORDER BY inBearbeitung DESC 
                              LIMIT 1");
        $qry->execute(array($this->column['benutzername']));
        $cell = $qry->fetch(PDO::FETCH_ASSOC);
        
        if($cell['inBearbeitung'] == 1) {
            return $cell['idMitarbeiter'];
        } else {
            return -1;
        }
    }
    
    // Verifies all mandatory fields stored in column[]
    private function verify()
    {
        // Check 'null' or '' (empty string)
        //if(in_array(null, $this->column) || in_array("", $this->column))
            //return false;
            
        // Values verified
        return true;
    }
}
?>